<?php
/**
 * Created by PhpStorm.
 * User: hui
 * Date: 2016/10/11
 * Time: 07:02
 */
namespace app\index\controller;

use think\Controller;
use think\Request;

class Gps extends Controller
{
    public function index()
    {
        //$url = 'http://api.map.baidu.com/trace/v2/entity/add';
        if (Request::instance()->isAjax()) {
            $url = 'http://api.map.baidu.com/trace/v2/track/addpoint';
            $gps = Request::instance()->post();
            $post = [
                'ak'          => 'RT8Z4fRlxrW2gGW5ApvMkd2pPaTHQGUo',
                'service_id'  => 126716,
                'entity_name' => 'test',
                'latitude'    => $gps['latitude'],
                'longitude'   => $gps['longitude'],
                'coord_type'  => 1,
                'loc_time'    => time(),
            ];
            $this->post($url, $post);
        } else {
            return $this->fetch('Index/gps');
        }
    }

    public function post($url, $post)
    {
        $str = '';
        foreach ($post as $key => $val) {
            $str .= $key . '=' . $val . '&';
        }
        var_dump(substr($str, 0, -1));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, count($post));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $str);

        ob_start();
        curl_exec($ch);
        $result = ob_get_contents();
        ob_end_clean();

        echo $result;

        curl_close($ch);
    }
}